//
//  DebugServer.m
//  iBasic
//
//  Created by Andrew Barry on 12/04/08.
//  Copyright 2008 Barry Computer Services. All rights reserved.
//

#import "DebugServer.h"
#import "DebugConnection.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

DebugServer *serverInstance;

@implementation DebugServer
+(DebugServer *) instance
{
	if (serverInstance == nil)
		serverInstance = [DebugServer new];
	return serverInstance;
}

-(void) startServer: (id) arg
{
	NSAutoreleasePool		* pool = [[NSAutoreleasePool alloc] init];

    int32_t i32SocketFD = socket(PF_INET, SOCK_STREAM, 0);
//	printf("server started\n");

	int on = 1;
	setsockopt( i32SocketFD, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) );

	
    struct sockaddr_in stSockAddr;
    bzero(&stSockAddr, sizeof(stSockAddr));
 
    stSockAddr.sin_family = AF_INET;
    stSockAddr.sin_port = htons(1100);
    stSockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
 
    if(-1 == bind(i32SocketFD,(struct sockaddr*) &stSockAddr, sizeof(stSockAddr)))
    {
      printf("error bind failed");
      return;
    }
 
    if(-1 == listen(i32SocketFD, 10))
    {
      printf("error listen failed");
	  return;
    }
 
    for(; ;)
    {
      int32_t i32ConnectFD = accept(i32SocketFD, NULL, NULL);
 
      if(0 > i32ConnectFD)
      {
        printf("error accept failed");
        return;
      }
 
		// hand off to other handler
		[NSThread detachNewThreadSelector:@selector(acceptConnection:) toTarget:[DebugConnection new] withObject:[NSNumber numberWithInt: i32ConnectFD]];
 
    }
	
	[pool release];
}

@end
